﻿using System.IO.IsolatedStorage;
using System.IO;

namespace AMing.Helper.WindowsPhone8
{
    public class FileHelper
    {
        /// <summary>
        /// 读取txt文本内容
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static string TxtFileRead(string filepath)
        {
            using (var appStora = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (appStora.FileExists(filepath))
                {
                    using (var stream = appStora.OpenFile(filepath, System.IO.FileMode.Open))
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
                else
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 保存Txt文件
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="txt"></param>
        public static void TxtFileWrite(string filepath, string txt)
        {
            using (var appStora = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string folder = System.IO.Path.GetDirectoryName(filepath);
                if (!appStora.DirectoryExists(folder))
                {
                    appStora.CreateDirectory(folder);
                }
                using (var stream = appStora.OpenFile(filepath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(stream))
                    {
                        sw.Write(txt);
                    }
                }
            }
        }
    }
}
